#!/usr/bin/perl

# Stop us from shooting outselves in the foot
use strict;
use warnings;
use FindBin qw($Bin);
use lib "$Bin";

use MDBUtils;
use MDBAWS;
use MDBWP;

# Configuration
my $config = MDBUtils::get_config();
my $queue  = MDBAWS::sqs_get_queue("wordpress");

while (1) {
    my $msg = MDBAWS::sqs_get_message($queue);

    if ( !defined($msg) ) {
        print "DEBUG: No tickets in the queue, quiting...\n";
        exit(0);
    }
    else {
        print "DEBUG: Picked up SQS ticket: " . $msg->MessageBody() . "\n";

        my $metadata = MDBAWS::sdb_get_metadata( $msg->MessageBody() );

        if ( defined( $metadata->{'sha256'} ) ) {
            if ( !defined( $metadata->{'wp_post'} ) ) {
                my $post_no = MDBWP::WPPost( $metadata->{'sha256'} );
                if ( defined($post_no) ) {
                    my $new_metadata;
                    $new_metadata->{'wp_post'} = $post_no;
                    $new_metadata->{'sha256'}  = $metadata->{'sha256'};
                    MDBAWS::sdb_put_metadata($new_metadata);
                }
            }
        }

        # Create SQS Ticket(s)
        MDBAWS::sqs_put_queue( "wordpress", $msg->MessageBody() );

        print "DEBUG: Deleting SQS ticket: " . $msg->MessageBody() . "\n";
        $queue->DeleteMessage( $msg->ReceiptHandle() );
    }
}
